//
//  YQLOAuthViewController.swift
//  YQL_WeiBo
//
//  Created by apple on 2016/11/15.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD


class YQLOAuthViewController: UIViewController,UIWebViewDelegate {
    
    
    //viewModle属性
//    var OAuthViewModel = YQLOAuthViewModel.shared
    
    //存储网络请求返回的用户信息数据
//    var userAccount: YQLUserInfoModel?
    
    let webView = UIWebView()
    
    //修改跟控制器
    override func loadView() {
        
        self.view = webView
        //设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置背景色
        webView.backgroundColor = UIColor.white

        //设置关闭和偷鸡按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(closeVC))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "偷鸡", target: self, action: #selector(touJi))
        
        //加载第三方登录页面
        loadOAuthPage()
    }
    //dismiss方法
    func closeVC() {
        
        self.navigationController?.dismiss(animated: true, completion: nil)
    }
    //填充用户名和密码,Swift调用JS
    func touJi() {
        
        let jsString = "document.getElementById('userId').value = '478924785@qq.com', document.getElementById('passwd').value = 'wsjlove1314'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    //加载WebView
    private func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "236082640" + "&redirect_uri=" + "http://www.baidu.com"
        let url = URL(string: urlString)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
        
    }
    //视图销毁的时候取消掉页面加载指示器
    override func viewWillDisappear(_ animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
        
    }
    

    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //webView发起网络请求的监听方法,获取code
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.url?.absoluteString ?? ""
        
        let str = "code="
        
        if urlString.contains(str) {
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: str.characters.count)
            print("code = ",code)
            YQLOAuthViewModel.shared.getAccesssToken(code: code, finish: { (isSuccess) in
                if !isSuccess{
                    SVProgressHUD.showError(withStatus: "加载token错误")
                    return
                }
                //请求成功,修改window的根控制器--> 使用通知的方式修改window的根控制器
                NotificationCenter.default.post(name: NSNotification.Name(KModifyRootViewControll), object: "OAuthVCPost")
//                UIApplication.shared.keyWindow?.rootViewController = YQLWelcomeViewController()
                //销毁登录的控制器
//                self.navigationController?.dismiss(animated: true, completion: nil)
                
                
            })
            return false
        }
        
        return true
    }
    
//    //获取code后发起网络请求获取AccessToken//https://api.weibo.com/oauth2/access_token
//    func getAccesssToken(code: String, finish: @escaping (Bool) -> ()) {
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        let parameters = ["client_id" : "236082640","client_secret" : "b328054250c1a80045713e7cd012db57","grant_type" : "authorization_code","code" : code,"redirect_uri" : "http://www.baidu.com"]
//        
//        DDNetworkTool.sharedManager.request(Method: .POST, urlString: urlString, parameters: parameters) { (responsObject, error) in
//            
//            if error != nil{
//                finish(false)
//                print(error as Any)
//                SVProgressHUD.showError(withStatus: "加载Token错误")
//                return
//            }
//            //请求成功,接下来请求用户信息数据
//            print("responseObject = ",responsObject as Any)
//            
//            self.loadUserInfo(dict: responsObject as! [String : Any], complete: finish)
//            
//        }
//        
//    }
//    
//    func loadUserInfo(dict: [String : Any], complete: @escaping (Bool) -> ()) {
//        
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        let token = dict["access_token"]
//        let uid = dict["uid"]
//        let parameters = ["access_token" : token,"uid" : uid];
//        DDNetworkTool.sharedManager.request(Method: .GET, urlString: urlString, parameters: parameters) { (responsObject, error) in
//            if error != nil {
//                print(error as Any)
//                SVProgressHUD.showError(withStatus: "加载用户信息失败")
//                complete(false)
//                return
//            }
//            //请求成功
//            print(responsObject as Any)
//            
//            var dictUserInfo: [String : Any] = responsObject as! [String : Any]
//            for (key,value) in dict{
//                
//                dictUserInfo[key] = value
//            }
//            
//            //字典转模型
//            let userInfoModel = YQLUserInfoModel(dict: dictUserInfo)
//            //归档
//            self.saveUserInfoModel(userInfo: userInfoModel)
//            //属性赋值
//            self.userAccount = userInfoModel
//            
//            complete(true)
//        }
//    }
//    
//    
//    //归档方法
//    func saveUserInfoModel(userInfo: YQLUserInfoModel) {
//        
//        //路径
//        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.plist")
//        
//        NSKeyedArchiver.archiveRootObject(userInfo, toFile: filePath)
//    }
//    
//    //解档方法
//    func loadUserInfoModel() -> YQLUserInfoModel? {
//        
//        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.plist")
//        
//        let model = NSKeyedUnarchiver.unarchiveObject(withFile: filePath)
//        if let userInfoModel = model as? YQLUserInfoModel {
//            return userInfoModel
//        }
//        return nil
//    }
//    
    
}




















